package com.niit.hbase;

import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * Date:2024/11/22
 * Author：Ys
 * Description:
 */
public class WordCountReduce extends TableReducer<Text, IntWritable, ImmutableBytesWritable> {

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, ImmutableBytesWritable, Mutation>.Context context) throws IOException, InterruptedException {

        if(key.toString().isEmpty()){
            return;
        }

        //定义并统计次数结果
        int sum = 0;
        for (IntWritable value : values) {
            sum += value.get();
        }

        //输出 Put对象， 单词作为RowKey 次数作为列值
        Put put = new Put(Bytes.toBytes(key.toString()));

        put.addColumn(  Bytes.toBytes("content"),Bytes.toBytes("count"),Bytes.toBytes(String.valueOf(sum)) );

        context.write(  new ImmutableBytesWritable(Bytes.toBytes(key.toString()) ),  put  );
    }
}
